using UnityEditor;
using UnityEditor.EditorTools;
using UnityEngine;

namespace GridSystem.Editor
{
    [EditorTool("PlaceableObject Grid Mover", typeof(PlaceableObject))]
    public class PlaceableObjectGridMover : EditorTool
    {
        private float _snapValue = 0.1f;
        private Rect _windowRect = new(5, 0, 200, 70);
        private bool _isInitialPositionSet = false;

        private static GUIContent _toolbarIcon;
        private static GUIContent ToolbarIcon
        {
            get
            {
                if (_toolbarIcon == null)
                {
                    _toolbarIcon = EditorGUIUtility.isProSkin ? EditorGUIUtility.IconContent("d_Grid.MoveTool") : EditorGUIUtility.IconContent("Grid.MoveTool");
                    _toolbarIcon.tooltip = "网格高度调整工具";
                }
                return _toolbarIcon;
            }
        }
        public override GUIContent toolbarIcon => ToolbarIcon;

        public override void OnToolGUI(EditorWindow window)
        {
            if (window is not SceneView sceneView) return;

            GridSurface surface = target as GridSurface;
            if (surface == null) return;

            Event e = Event.current;

            if (!_isInitialPositionSet || e.type == EventType.Layout)
            {
                _windowRect.y = sceneView.position.height - _windowRect.height - 30;
                _isInitialPositionSet = true;
            }

            Transform targetTransform = surface.transform;

            EditorGUI.BeginChangeCheck();

            float newYOffset;
            using (new Handles.DrawingScope(targetTransform.localToWorldMatrix))
            {
                newYOffset = Handles.Slider(
                    Vector3.up * surface.yOffset,
                    Vector3.up,
                    HandleUtility.GetHandleSize(Vector3.up * surface.yOffset) * 1f,
                    Handles.ArrowHandleCap,
                    _snapValue
                ).y;
            }

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(surface, "修改GridSurface的yOffset");
                surface.yOffset = newYOffset;
                EditorUtility.SetDirty(surface);
            }

            Handles.BeginGUI();
            _windowRect = GUILayout.Window(GetHashCode(), _windowRect, DrawToolWindow, "网格高度调整工具");
            // 限制窗口在Scene视图内
            _windowRect.x = Mathf.Clamp(_windowRect.x, 5, sceneView.position.width - _windowRect.width - 5);
            _windowRect.y = Mathf.Clamp(_windowRect.y, 0, sceneView.position.height - _windowRect.height - 30); // 留出底部栏空间
            Handles.EndGUI();

            sceneView.Repaint();
        }

        private void DrawToolWindow(int id)
        {
            EditorGUILayout.LabelField("按住 [Ctrl] 使用吸附功能");
            _snapValue = EditorGUILayout.FloatField("吸附值", _snapValue);
            GUI.DragWindow();
        }
    }
}